package com.dominator.serviceImpl;

import com.dominFramework.core.dao.SqlDao;
import com.dominFramework.core.id.SystemIdUtils;
import com.dominFramework.core.typewrap.Dto;
import com.dominFramework.core.typewrap.Dtos;
import com.dominFramework.core.utils.SystemUtils;
import com.dominator.enums.ReqEnums;
import com.dominator.mybatis.dao.T_accountPO;
import com.dominator.mybatis.dao.T_game_orderDao;
import com.dominator.mybatis.dao.T_game_orderPO;
import com.dominator.mybatis.dao.T_userPO;
import com.dominator.repository.DaoGameOrder;
import com.dominator.service.ApiAccountService;
import com.dominator.service.ApiGameOrderService;
import com.dominator.service.ApiMachineService;
import com.dominator.service.ApiUserService;
import com.dominator.socket.SocketService;
import com.dominator.utils.api.ApiMessage;
import com.dominator.utils.api.ApiMessageUtil;
import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import com.dominator.utils.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service("ApiGameOrderService")
public class ApiGameOrderServiceImpl implements ApiGameOrderService {

    @Autowired
    T_game_orderDao tGameOrderDao;
    @Autowired
    DaoGameOrder daoGameOrder;

    @Autowired
    ApiAccountService apiAccountService;

    @Autowired
    SqlDao sqlDao;


    @Autowired
    ApiMachineService apiMachineService;

    @Autowired
    ApiGameOrderService apiGameOrderService;


    @Autowired
    ApiUserService apiUserService;



    private RedisUtil ru = RedisUtil.getRu();



    @Override
    public ApiMessage addGameOrder(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "userId,prizeId");
        T_game_orderPO t_game_orderPO = new T_game_orderPO();
        t_game_orderPO.setId(SystemIdUtils.uuid());
        t_game_orderPO.setCreate_time(new Date());
        t_game_orderPO.setIs_valid("1");
        t_game_orderPO.setIs_back("0");
        t_game_orderPO.setGame_id("1");
        t_game_orderPO.setGame_price_id(dto.getString("prizeId"));
        t_game_orderPO.setUser_id(dto.getString("userId"));
        t_game_orderPO.setMachine_id(dto.getString("machineId"));
        t_game_orderPO.setMachine_name(dto.getString("machineName"));
        t_game_orderPO.setShop_name(dto.getString("shopName"));

        //test
        t_game_orderPO.setGua_ticket_id(SystemIdUtils.uuid());
        t_game_orderPO.setOrder_status("1");
        t_game_orderPO.setIs_prize("1");
        t_game_orderPO.setPrize_money(new BigDecimal(Math.random()).multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_UP));






        tGameOrderDao.insert(t_game_orderPO);
        Dto resDto =Dtos.newDto();
        //查询用户余额
        T_accountPO accountPO = apiAccountService.getAccountByUserId(dto.getString("userId"));
        resDto.put("userId",dto.getString("userId"));
        resDto.put("amount",accountPO.getMoney());
        resDto.put("gameOrderId",t_game_orderPO.getId());

        //游戏设置状态
        dto.put("gameStatus","1");
        setGameStatus(dto);

        return ApiMessageUtil.success(resDto);
    }

    @Override
    public ApiMessage queryOrderStatus(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "gameOrderId");
        T_game_orderPO tGameOrderPO = tGameOrderDao.selectByKey(dto.getString("gameOrderId"));
        Dto resDto =Dtos.newDto();
        if (SystemUtils.isEmpty(tGameOrderPO)) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_EXSIT);
        }else if ("0".equals(tGameOrderPO.getIs_valid())) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_VALID);
        } else if ("1".equals(tGameOrderPO.getIs_back())) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_BACK);
        }else if (SystemUtils.isEmpty(tGameOrderPO.getGua_ticket_id())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_GUA);
        }else if (SystemUtils.isEmpty(tGameOrderPO.getOrder_status())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_GUA);
        }else if (SystemUtils.isEmpty(tGameOrderPO.getIs_prize())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_GUA);
        }else if (SystemUtils.isEmpty(tGameOrderPO.getPrize_money())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_GUA);
        }else {
            resDto.put("gameOrderId",tGameOrderPO.getId());
            resDto.put("isPrize",tGameOrderPO.getIs_prize());
            resDto.put("prizeMoney",tGameOrderPO.getPrize_money());
            resDto.put("guaTicketId",tGameOrderPO.getGua_ticket_id());
            resDto.put("prizeList",new ArrayList<>());
        }
        return  ApiMessageUtil.success(resDto);
    }

    @Override
    public ApiMessage addGameGoods(Dto dto) throws ApiException {
        return null;
    }


    @Override
    public boolean isGaming(Dto dto) throws ApiException {
        String gameStatus = ru.hmget("game:gu_" + dto.getString("userId"), "gameStatus").get(0);
        return "0".equals(gameStatus)?false:true;
    }

    @Override
    public ApiMessage modifyGameOrder(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "gameOrderId,isPrize,guaTicketId");
        T_game_orderPO tGameOrderPO = tGameOrderDao.selectByKey(dto.getString("gameOrderId"));
        if (SystemUtils.isEmpty(tGameOrderPO)) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_EXSIT);
        } else if ("1".equals(tGameOrderPO.getIs_back())) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_BACK);
        }
        tGameOrderPO.setGua_ticket_id(dto.getString("guaTicketId"));
        tGameOrderPO.setIs_prize(dto.getString("isPrize"));
        if ("0".equals(dto.getString("isPrize"))) {
            tGameOrderPO.setPrize_money(BigDecimal.ZERO);
        } else if ("1".equals(dto.getString("isPrize"))) {
            tGameOrderPO.setPrize_money(dto.getBigDecimal("prizeMoney"));
        }
        dto.put("userId", tGameOrderPO.getUser_id());
        tGameOrderDao.updateByKey(tGameOrderPO);
        //开奖通知
//        dto.put("method","ApiGameOrderService.gameResultNotification");
//        dto.put("machineId",tGameOrderPO.getMachine_id());
//        Dto contentDto = Dtos.newDto();
//        contentDto.put("gameOrderId",dto.getString("gameOrderId"));
//        contentDto.put("isPrize",dto.getString("isPrize"));
//        contentDto.put("prizeMoney","0".equals(dto.getString("isPrize"))?BigDecimal.ZERO:dto.getBigDecimal("prizeMoney"));
//        contentDto.put("guaTicketId",dto.getString("guaTicketId"));
//        dto.put("content",contentDto);
//        try {
//            apiMachineService.sendToMachineId(dto);
//        }catch (Exception e){
//            log.error(e.getMessage());
//            e.printStackTrace();
//        }
        return ApiMessageUtil.success();
    }



    @Override
    public ApiMessage getOrderByUserId(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "userId");
        dto.setPageLimit(dto.getInteger("pageLimit"));
        dto.setPageStart(dto.getInteger("pageStart"));
        return ApiMessageUtil.success(daoGameOrder.getOrderByDtoPage(dto));
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public ApiMessage reportGameOver(Dto dto) throws ApiException {
        //上报游戏结束
        ApiUtils.checkParam(dto, "gameOrderId");
       T_game_orderPO tGameOrderPO = tGameOrderDao.selectByKey(dto.getString("gameOrderId"));
        if (SystemUtils.isEmpty(tGameOrderPO)) {
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_EXSIT);
        }else if ("1".equals(tGameOrderPO.getIs_back())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_BACK);
        }else if ("0".equals(tGameOrderPO.getIs_valid())){
            throw new ApiException(ReqEnums.GAME_ORDER_IS_NOT_VALID);
        }else if ("1".equals(tGameOrderPO.getIs_prize())){
            //游戏状态
            Map<String, String> map = new HashMap<String, String>();
            map.put("gameStatus", "0");
            ru.hmset("game:gu_" + tGameOrderPO.getUser_id(), map);
            //订单状态
            tGameOrderPO.setIs_back("1");
            tGameOrderPO.setOrder_status("1");
            tGameOrderPO.setModify_time(new Date());
            tGameOrderDao.updateByKey(tGameOrderPO);
            //返奖
            dto.put("userId", tGameOrderPO.getUser_id());
            dto.put("money", tGameOrderPO.getPrize_money());
            apiAccountService.addMoney(dto);
        }
        //查询最新状态
        T_accountPO tAccountPO=apiAccountService.getAccountByUserId(tGameOrderPO.getUser_id());
        Dto resDto=Dtos.newDto();
        resDto.put("userId",tGameOrderPO.getUser_id());
        resDto.put("amount",tAccountPO.getMoney());
        resDto.put("machineId",tGameOrderPO.getMachine_id());
        return ApiMessageUtil.success(resDto);
    }

    @Override
    public ApiMessage getUnFillingOrder(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto,"gamePriceId");
        List<T_game_orderPO> list =daoGameOrder.getUnFillingOrder(dto);
        Dto  resDto= Dtos.newDto();
        resDto.put("unFillingOrders",list.size());
        return ApiMessageUtil.success(resDto);
    }


    public ApiMessage setGameStatus(Dto dto) throws ApiException {
        ApiUtils.checkParam(dto, "userId,gameStatus");
        Map<String, String> map = new HashMap<String, String>();
        map.put("gameStatus",dto.getString("gameStatus"));
        ru.hmset("game:gu_"+dto.getString("userId"),map);
        return ApiMessageUtil.success();
    }

}
